<template>
  <div class="page-container">
    <OpinionVerticalTabNav />
    
    <div class="opinion-source-container">
      <!-- 标题栏与返回按钮 -->
      <div class="page-header">
        <div class="left-area">
          <h2 class="page-title">舆情来源管理</h2>
        </div>
        <div class="right-area">
          <el-button type="primary" @click="handleAdd" class="custom-button">
            <el-icon><Plus /></el-icon>新增来源
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        height="calc(100vh - 250px)"
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="来源名称" prop="sourceName" min-width="150" />
        <el-table-column label="渠道类型" prop="sourceType" width="120" align="center" />
        <el-table-column label="原始链接" prop="sourceUrl" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <a 
              :href="scope.row.sourceUrl" 
              target="_blank" 
              class="source-link"
              v-if="scope.row.sourceUrl"
            >{{ scope.row.sourceUrl }}</a>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="可信度" prop="credibilityLevel" width="120" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.credibilityLevel"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增舆情来源' : '编辑舆情来源'"
        width="50%"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="来源名称" prop="sourceName">
            <el-input v-model="form.sourceName" placeholder="请输入来源名称，如：微博、新闻网站" />
          </el-form-item>
          <el-form-item label="渠道类型" prop="sourceType">
            <el-select v-model="form.sourceType" placeholder="请选择渠道类型" style="width: 100%">
              <el-option label="社交媒体" value="社交媒体" />
              <el-option label="新闻网站" value="新闻网站" />
              <el-option label="论坛" value="论坛" />
              <el-option label="官方发布" value="官方发布" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="原始链接" prop="sourceUrl">
            <el-input v-model="form.sourceUrl" placeholder="请输入原始链接" />
          </el-form-item>
          <el-form-item label="可信度级别" prop="credibilityLevel">
            <el-rate
              v-model="form.credibilityLevel"
              :max="5"
              :texts="['1级(最低)', '2级', '3级', '4级', '5级(最高)']"
              show-text
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { 
  getPublicOpinionList, 
  getPublicOpinionById, 
  addPublicOpinion, 
  updatePublicOpinion, 
  deletePublicOpinion 
} from "@/api/bridge/bisc/public-opinion";
import OpinionVerticalTabNav from '../components/OpinionVerticalTabNav.vue';

// 路由
const router = useRouter();

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");

// 表单数据
const formRef = ref();
const form = ref({
  id: "",
  sourceName: "",
  sourceType: "",
  sourceUrl: "",
  credibilityLevel: 3,
});

// 表单校验规则
const rules = {
  sourceName: [{ required: true, message: "请输入来源名称", trigger: "blur" }],
  sourceType: [{ required: true, message: "请选择渠道类型", trigger: "change" }],
  credibilityLevel: [{ required: true, message: "请选择可信度级别", trigger: "change" }],
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    queryParams.pageNum = currentPage.value;
    queryParams.pageSize = pageSize.value;

    const res = await getPublicOpinionList(queryParams);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error("获取舆情来源列表失败:", error);
    ElMessage.error("获取舆情来源列表失败");
  } finally {
    loading.value = false;
  }
};

// 返回舆情列表
const goBack = () => {
  router.push('/basic-data/public-opinion');
};

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  form.value = {
    id: "",
    sourceName: "",
    sourceType: "",
    sourceUrl: "",
    credibilityLevel: 3,
  };
  dialogVisible.value = true;
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    loading.value = true;
    const res = await getPublicOpinionById(row.id);
    dialogType.value = "edit";
    form.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取舆情来源详情失败:", error);
    ElMessage.error("获取舆情来源详情失败");
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该舆情来源吗？删除后可能影响关联的舆情数据", "警告", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deletePublicOpinion(row.id);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        console.error("删除舆情来源失败:", error);
        ElMessage.error("删除舆情来源失败");
      }
    })
    .catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await addPublicOpinion(form.value);
          ElMessage.success("新增成功");
        } else {
          await updatePublicOpinion(form.value);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.opinion-source-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .left-area {
    display: flex;
    align-items: center;
    gap: 12px;

    .back-button {
      display: flex;
      align-items: center;
      gap: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateX(-2px);
      }
    }

    .page-title {
      margin: 0;
      font-size: 18px;
      color: var(--el-text-color-primary);
      position: relative;
      padding-left: 15px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: var(--el-color-primary);
        border-radius: 2px;
      }
    }
  }

  .right-area {
    .custom-button {
      position: relative;
      overflow: hidden;
      transition: all 0.3s ease;

      &::before {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: width 0.6s ease, height 0.6s ease;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        &::before {
          width: 300px;
          height: 300px;
        }
      }

      &:active {
        transform: translateY(1px);
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.source-link {
  color: var(--el-color-primary);
  text-decoration: none;
  position: relative;
  
  &:hover {
    text-decoration: underline;
  }
  
  &::after {
    content: "\f08e";
    font-family: "Element Icons";
    margin-left: 4px;
    font-size: 12px;
  }
}
</style> 